import { pageOpeTypeEnum } from '@/common';
import { getIndustryList } from '@/redux/toolkitSlice/CommonDataSlice';
import { App, Button, Space } from 'antd';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useNavigate, useSearchParams } from 'react-router-dom';
import type { YmAddPageLayoutProps } from 'ym-design';
import { YmAddPageLayout } from 'ym-design';
import AddCircleStudyPlan from './AddCircleStudyPlan';
import AddFixedStudyPlan from './AddFixedStudyPlan';
import PositionInfo from './components/PositionInfo';
import { StudyPlanChildRef } from './interface';
import OfflineStudyPlan from './OfflineStudyPlan';

const { PaneItem } = YmAddPageLayout;

function AddStudyPlan() {
  const dispatch = useDispatch();
  const { message } = App.useApp();
  const [searchParam] = useSearchParams();
  const navigator = useNavigate();
  const type = searchParam.get('type') as any;
  const studyMethod = searchParam.get('studyMethod') === '200' ? '200' : '100'; // '200': 线下培训, '100': 线上学习 (type === 'edit'时用)
  const planType = searchParam.get('planType') === '100' ? 'fixed' : 'circle'; //'100':固定时间，'200'：循环 (type === 'edit'时用)
  const planCourseId = searchParam.get('planCourseId') || undefined;
  const previewDetail = searchParam.get('previewDetailStr')
    ? JSON.parse(searchParam.get('previewDetailStr') as string)
    : undefined;

  const studyPlanRef = useRef<StudyPlanChildRef>(null);

  const [loadingDetail, setLoadingDetail] = useState({
    subBtnDis: false,
    viewLoading: false,
  });
  const [learnMethod, setLearnMethod] = useState<'200' | '100'>(studyMethod || '100');
  const [studyPlanType, setStudyPlanType] = useState<'circle' | 'fixed'>(planType || 'circle');

  // const [formIndex] = Form.useForm();
  // const { entId, organizationType } = useAppSelector((state) => state.loginEnt); //organizationType 1:协会，0：企业
  useEffect(() => {
    dispatch(getIndustryList());
  }, []);

  //发布
  const onSubPublish = () => {
    studyPlanRef.current?.onSubPublish();
  };

  // 保存
  const onSubSave = () => {
    studyPlanRef.current?.onSubSave?.();
  };
  const operationFooter = useMemo(() => {
    const opeBtnList = [
      <Button key="public" type="primary" size="small" disabled={loadingDetail.subBtnDis} onClick={onSubPublish}>
        发布
      </Button>,
    ];
    if (studyPlanType === 'fixed' || learnMethod === '200') {
      opeBtnList.push(
        <Button key="save" type="primary" size="small" disabled={loadingDetail.subBtnDis} onClick={onSubSave}>
          保存
        </Button>,
      );
    }
    return opeBtnList;
  }, [studyPlanType, loadingDetail, studyPlanRef, learnMethod]);

  const layoutParams: YmAddPageLayoutProps = useMemo(
    () => ({
      leftOperation: {
        onBack: () => {
          navigator('/plannedManage/studyPlan');
        },
      },
      rightOperationDom: operationFooter,
      destroyInactiveTabPane: false,
    }),
    [operationFooter],
  );
  return (
    <YmAddPageLayout {...layoutParams}>
      <PaneItem
        tabKey="tab1"
        label={(type === pageOpeTypeEnum['add'] ? '添加' : '编辑') + '学习计划'}
        className="pane_tab1"
      >
        <div className="ym_detail_grid">
          <PositionInfo />
          {learnMethod === '200' ? (
            <OfflineStudyPlan
              ref={studyPlanRef}
              onSubSuccess={() => {
                // navigator(-1);
                navigator('/plannedManage/studyPlan');
              }}
              onSubError={() => {
                setLoadingDetail({ subBtnDis: false, viewLoading: false });
              }}
              onStudyPlanMethodChange={setLearnMethod}
              learnMethod={learnMethod}
              onStudyPlanTypeChange={setStudyPlanType}
              studyPlanType={studyPlanType}
              type={type!}
              planCourseId={planCourseId}
              previewDetail={previewDetail}
            />
          ) : studyPlanType === 'circle' ? (
            <AddCircleStudyPlan
              ref={studyPlanRef}
              onSubSuccess={() => {
                // navigator(-1);
                navigator('/plannedManage/studyPlan');
              }}
              onSubError={() => {
                setLoadingDetail({ subBtnDis: false, viewLoading: false });
              }}
              onStudyPlanMethodChange={setLearnMethod}
              learnMethod={learnMethod}
              onStudyPlanTypeChange={setStudyPlanType}
              studyPlanType={studyPlanType}
              type={type!}
              planCourseId={planCourseId}
              previewDetail={previewDetail}
            />
          ) : (
            <AddFixedStudyPlan
              ref={studyPlanRef}
              onSubSuccess={() => {
                // navigator(-1);
                navigator('/plannedManage/studyPlan');
              }}
              onSubError={() => {
                setLoadingDetail({ subBtnDis: false, viewLoading: false });
              }}
              onStudyPlanMethodChange={setLearnMethod}
              learnMethod={learnMethod}
              onStudyPlanTypeChange={setStudyPlanType}
              studyPlanType={studyPlanType}
              type={type!}
              planCourseId={planCourseId}
              previewDetail={previewDetail}
            />
          )}
        </div>
        {operationFooter && (
          <div className="yn_detail_operation_footer">
            <Space direction="horizontal" size="small">
              {operationFooter}
            </Space>
          </div>
        )}
      </PaneItem>
    </YmAddPageLayout>
  );
}

export default AddStudyPlan;
